package apps

var RootTpl = `package cmd

import (
    "fmt"
    "github.com/spf13/cobra"
    "go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc"
    "google.golang.org/grpc"
    "google.golang.org/grpc/health"
    healthpb "google.golang.org/grpc/health/grpc_health_v1"
    "log"
    "net"
    "os"
    "{{.App}}/pkg/storage/chain"
    "{{.App}}/pkg/storage/conf"
    "{{.App}}/pkg/storage/consul"
    "{{.App}}/pkg/storage/db"
    "{{.App}}/pkg/storage/verify"
    "{{.App}}/proto/pb"
    "{{.App}}/srv/internal/logic"
)

var rootCmd = &cobra.Command{
    Use:   "srv",
    Short: "A brief description of your application",
    Long:  "A longer description of your application, more detailed",
    Run: func(cmd *cobra.Command, args []string) {
        SrvRun()
    },
}

func Execute() {
    err := rootCmd.Execute()
    if err != nil {
        os.Exit(1)
    }
}

func SrvRun() {
    conf.Init()
    db.Init()
    verify.Init()
    if conf.Cfg.Chain.Enable == true {
        err := chain.JaegerInit()
        if err != nil {
            fmt.Println("调用链错误")
            os.Exit(1)
        }
    }

    cfg := conf.Cfg.Consul
    lis, err := net.Listen("tcp", "127.0.0.1:8889")
    if err != nil {
        log.Fatal("服务监听失败")
    }
    s := grpc.NewServer(grpc.StatsHandler(otelgrpc.NewServerHandler()))

    pb.RegisterVisrvServer(s, &logic.UserServer{})

    healthSrv := health.NewServer()
    healthpb.RegisterHealthServer(s, healthSrv)
    healthSrv.SetServingStatus("1", healthpb.HealthCheckResponse_SERVING)

    consulC, err := consul.NewConsul(fmt.Sprintf("%s:%d", cfg.Host, cfg.Port))
    if err != nil {
        fmt.Println(err)
        return
    }

    for _, srv := range cfg.Services {
        err = consulC.RGService(srv)
        if err != nil {
            fmt.Println(err)
            log.Fatalf("failed to register service with consul: %v", err)
        }
    }

    if err = s.Serve(lis); err != nil {
        fmt.Println(err)
        fmt.Println("服务端启动失败?")
    }
}
`
